package net.omnivention.proxy;

import org.apache.log4j.Logger;

public class HttpResponse {
	private static Logger logger = Logger.getLogger(HttpResponse.class);

	private int reponseCode;

	private String version;

	private HttpHeaders header;

	private HttpBody body;

	private String firstLine;

	void injectStatusLine(String line) {
		try {
			this.firstLine = line;
			String[] f = line.split(" "); // HTTP/1.0 200 OK
			String[] v = f[0].split("/");
			version = v[1];
			reponseCode = Integer.parseInt(f[1]);
		} catch (Exception ex) {
			logger.error("line="+line);
			logger.error(ex);
			ex.printStackTrace();
		}
	}

	public int getReponseCode() {
		return reponseCode;
	}

	public void setReponseCode(int reponseCode) {
		this.reponseCode = reponseCode;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public void setHeader(HttpHeaders header) {
		this.header = header;
	}

	public HttpHeaders getHeader() {
		return header;
	}

	public HttpBody getBody() {
		return body;
	}

	public void setBody(HttpBody body) {
		this.body = body;
	}

	public byte[] getAsByteArray() {
		byte[] first = (firstLine + "\n").getBytes();
		byte[] headers = (header.toString() + "\n").getBytes();
		byte[] content = body.getAsByteArray();

		byte[] response = new byte[first.length + headers.length + content.length];

		int i = 0;

		for (byte b : first) {
			response[i++] = b;
		}

		for (byte b : headers) {
			response[i++] = b;
		}

		for (byte b : content) {
			response[i++] = b;
		}
		return response;
	}

	public String toString() {
		return new String(getAsByteArray());
	}

}
